package com.my.admin.config.shiro.auto;

import com.my.admin.service.ShiroService;
import com.my.admin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ShiroService shiroService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(userService.getRoleByUserName(username));
        info.setStringPermissions(userService.getMenuByUserName(username));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        if(!shiroService.isToken(token)) {
            throw new IncorrectCredentialsException("token已失效，请重新登录！");
        }
        Map<Object, Object> map = shiroService.getTokenInfo(token);
        shiroService.updateToken(token);
        return new SimpleAuthenticationInfo(map.get("userId"), token, getName());
    }
}
